package com.example.utils;

import okhttp3.*;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * @Authror Lionet
 * @Date 2020/4/15 10:57
 * @Description 测试 OKhttp3 日志采集
 * 本方法目前只记录 POST 请求 参数, get 请求暂时不会记录参数
 */
public class Okhttp3GatherLoggerFilter implements Interceptor {

    private static final String TAG = "  拦截 Okhttp3 日志记录 ";


    private static final Logger logger = LoggerFactory.getLogger(Okhttp3GatherLoggerFilter.class);


    /**
     * @Author: Lionet
     * @Date 2020/4/15 13:31
     * @Description Okhttp 日志拦截类方法
     * 作用 :
     * 记录使用 okhttp 调用第三方时记录请求参数,响应结果
     * 请求第三方接口消耗时间
     * 追踪日志  warn采集
     * @Param:
     * @Return:
     */
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        ResponseBody responseBody = response.body();
        if (responseBody == null) {
            return response;
        }
        MediaType mediaType = responseBody.contentType();
        String content = response.body().string();
        //  logger.warn(TAG + " 请求地址: {}, 请求状态: {}  ", request.url().host(), response.code() + " : " + response.message());
        String method = request.method();
        String params = "";
        if ("POST".equals(method)) {
            Buffer buffer = new Buffer();
            try {
                request.body().writeTo(buffer);
                Charset charset = Charset.forName("UTF-8");
                MediaType contentType = request.body().contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF_8);
                }
                params = buffer.readString(charset);
              /*  logger.warn(TAG + " 请求地址: {}, 请求状态: {} 请求参数: {},  ", request.url().host(), response.code() + " : " + response.message());
                logger.warn(TAG + "  ", params);*/
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        logger.debug(TAG +
                        " 请求地址: {}," +
                        " 请求状态: {},  " +
                        " 请求参数: {},  " +
                        "响应结果: {}, " +
                        "请求耗时: {} ",
                request.url(),
                response.code() + " : " + response.message(),
                params,
                content,
                duration + "毫秒");

//    logger.warn(TAG + "  " + duration + "毫秒");
        return response.newBuilder().body(ResponseBody.create(mediaType, content)).build();
    }
}
